
from flask import request, jsonify, session
from auth_database import AuthDatabase
from auth_utils import login_required, admin_required, set_user_session, clear_user_session, get_current_user

auth_db = AuthDatabase()


def register_auth_routes(app):



    @app.route('/api/auth/register', methods=['POST'])
    def api_register():
        try:
            data = request.get_json()

            username = data.get('username', '').strip()
            password = data.get('password', '')
            email = data.get('email', '').strip()


            if not username or not password or not email:
                return jsonify({
                    'error': '请填写所有字段',
                    'success': False
                }), 400

            if len(username) < 3:
                return jsonify({
                    'error': '用户名至少3个字符',
                    'success': False
                }), 400

            if len(password) < 6:
                return jsonify({
                    'error': '密码至少6个字符',
                    'success': False
                }), 400


            if auth_db.check_username_exists(username):
                return jsonify({
                    'error': '用户名已存在',
                    'success': False
                }), 400


            if auth_db.check_email_exists(email):
                return jsonify({
                    'error': '邮箱已被注册',
                    'success': False
                }), 400


            user_id = auth_db.create_user(username, password, email, role='user')

            return jsonify({
                'success': True,
                'message': '注册成功',
                'user_id': user_id
            })

        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/auth/login', methods=['POST'])
    def api_login():
        try:
            data = request.get_json()

            username = data.get('username', '').strip()
            password = data.get('password', '')

            if not username or not password:
                return jsonify({
                    'error': '请填写用户名和密码',
                    'success': False
                }), 400


            success, result = auth_db.verify_user(username, password)

            if not success:
                return jsonify({
                    'error': result,
                    'success': False
                }), 401


            set_user_session(result)
            session.permanent = True

            return jsonify({
                'success': True,
                'message': '登录成功',
                'user': {
                    'id': result['id'],
                    'username': result['username'],
                    'role': result['role'],
                    'email': result['email']
                }
            })

        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/auth/logout', methods=['POST'])
    @login_required
    def api_logout():
        clear_user_session()
        return jsonify({
            'success': True,
            'message': '已登出'
        })


    @app.route('/api/auth/current', methods=['GET'])
    @login_required
    def api_current_user():
        user = get_current_user()
        user_data = auth_db.get_user(user['id'])

        return jsonify({
            'success': True,
            'user': {
                'id': user_data['id'],
                'username': user_data['username'],
                'email': user_data['email'],
                'role': user_data['role'],
                'xunfei_token_limit': user_data['xunfei_token_limit'],
                'qwen_token_limit': user_data['qwen_token_limit'],
                'xunfei_tokens_used': user_data['xunfei_tokens_used'],
                'qwen_tokens_used': user_data['qwen_tokens_used'],
                'is_active': user_data['is_active']
            }
        })




    @app.route('/api/admin/users', methods=['GET'])
    @admin_required
    def api_admin_get_users():
        try:
            users = auth_db.get_all_users()
            return jsonify({
                'success': True,
                'users': users
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/admin/users/<int:user_id>/tokens', methods=['PUT'])
    @admin_required
    def api_admin_update_tokens(user_id):
        try:
            data = request.get_json()

            xunfei_limit = data.get('xunfei_limit')
            qwen_limit = data.get('qwen_limit')

            auth_db.update_user_tokens(user_id, xunfei_limit, qwen_limit)

            return jsonify({
                'success': True,
                'message': 'Token限制已更新'
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/admin/users/<int:user_id>/freeze', methods=['POST'])
    @admin_required
    def api_admin_freeze_user(user_id):
        try:
            auth_db.freeze_user(user_id)
            return jsonify({
                'success': True,
                'message': '用户已冻结'
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/admin/users/<int:user_id>/unfreeze', methods=['POST'])
    @admin_required
    def api_admin_unfreeze_user(user_id):
        try:
            auth_db.unfreeze_user(user_id)
            return jsonify({
                'success': True,
                'message': '用户已解冻'
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/admin/users/<int:user_id>', methods=['DELETE'])
    @admin_required
    def api_admin_delete_user(user_id):
        try:

            current_user = get_current_user()
            if current_user['id'] == user_id:
                return jsonify({
                    'error': '不能删除自己的账号',
                    'success': False
                }), 400

            auth_db.delete_user(user_id)
            return jsonify({
                'success': True,
                'message': '用户已删除'
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500


    @app.route('/api/admin/users/<int:user_id>/reset-tokens', methods=['POST'])
    @admin_required
    def api_admin_reset_tokens(user_id):
        try:
            auth_db.reset_user_tokens(user_id)
            return jsonify({
                'success': True,
                'message': 'Token使用量已重置'
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500




    @app.route('/api/history', methods=['GET'])
    @login_required
    def api_get_history():
        try:
            user = get_current_user()
            limit = request.args.get('limit', 50, type=int)

            history = auth_db.get_user_history(user['id'], limit)

            return jsonify({
                'success': True,
                'history': history
            })
        except Exception as e:
            return jsonify({
                'error': str(e),
                'success': False
            }), 500
